// * 静态路由数据
import { constantRoutes } from '@/router'

import { getRouters } from '@/api/user'

import Layout from '@/layout/index'

/**
 * * routes 所有路由对象数组
 * * addRoutes 添加的路由（可以是从服务器获取的数据列表）
 */
const state = {
  routes: [],
  addRoutes: [],
}

const mutations = {
  // * 设置路由
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
}

const actions = {
  // * 请求服务器获取动态路由，生成最终路由
  generateRoutes({ commit }) {
    return new Promise((resolve) => {
      getRouters().then((res) => {
        const accessedRoutes = filterAsyncRouter(res.data)
        accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  },
}

// * 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter((route) => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    // ! 存在下层路由，处理下层路由数组
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

// ! 路由懒加载
export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default { state, mutations, actions }
